<?php

namespace app\admin\controller\example;

use app\common\controller\Backend;
use think\Db;

/**
 * 统计图表示例
 *
 * @icon   fa fa-charts
 * @remark 展示在FastAdmin中使用Echarts展示丰富多彩的统计图表
 */
class Echarts extends Backend
{

   protected $noNeedLogin = ['getData'];
    protected $model = null;
    

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('AdminLog');
    }

   
    /**
     * 获取平均视力数据
     */
    public function getAvgData($records, $vision)
    {
        // 初始化计数器和总和
        $naked_left_count = 0;
        $naked_right_count = 0;
        $glasses_left_count = 0;
        $glasses_right_count = 0;

        $naked_left_sum = 0;
        $naked_right_sum = 0;
        $glasses_left_sum = 0;
        $glasses_right_sum = 0;

        // 遍历记录并统计数量和视力总和
        foreach ($records as $record) {
            if ($record['naked_left'] == $vision) {
                $naked_left_count++;
                $naked_left_sum += $record['naked_left'];
            }
            if ($record['naked_right'] == $vision) {
                $naked_right_count++;
                $naked_right_sum += $record['naked_right'];
            }
            if ($record['glasses_left'] == $vision) {
                $glasses_left_count++;
                $glasses_left_sum += $record['glasses_left'];
            }
            if ($record['glasses_right'] == $vision) {
                $glasses_right_count++;
                $glasses_right_sum += $record['glasses_right'];
            }
        }

        // 计算平均视力
        $naked_left_avg = $naked_left_count > 0 ? $naked_left_sum / $naked_left_count : null;
        $naked_right_avg = $naked_right_count > 0 ? $naked_right_sum / $naked_right_count : null;
        $glasses_left_avg = $glasses_left_count > 0 ? $glasses_left_sum / $glasses_left_count : null;
        $glasses_right_avg = $glasses_right_count > 0 ? $glasses_right_sum / $glasses_right_count : null;

        return [
            ['value' => $naked_left_avg, 'name' => '裸眼左眼平均视力'],
            ['value' => $naked_right_avg, 'name' => '裸眼右眼平均视力'],
            ['value' => $glasses_left_avg, 'name' => '戴镜左眼平均视力'],
            ['value' => $glasses_right_avg, 'name' => '戴镜右眼平均视力']
        ];
    }
   public function line(){
 
    $vision1 = $this->request->post('schoolname', '');
    if (empty($vision1)) {
        $this->error('未选择学校！请先选择学校');
    }
    $params = $this->request->post();
    $params = array_filter($params, function($value) {
        return !is_null($value) && $value !== '';
    });
    
   
    $filteredRecords = Db::name('student_reports')
    ->where($params)
    ->select();
    if (empty($filteredRecords)) {
        $this->error('没有数据');
    }
    $monthlyData = [];

    foreach ($filteredRecords as $record) {
        $month = $record['month'];

        if (!isset($monthlyData[$month])) {
            $monthlyData[$month] = [
                'naked_left_count' => 0,
                'naked_right_count' => 0,
                'glasses_left_count' => 0,
                'glasses_right_count' => 0,
                'naked_left_sum' => 0,
                'naked_right_sum' => 0,
                'glasses_left_sum' => 0,
                'glasses_right_sum' => 0,
            ];
        }

         // 检查每个字段是否为0，如果不为0则进行累加
         if ($record['naked_left'] !== '0.0' && $record['naked_left'] !== null) {
            $monthlyData[$month]['naked_left_count']++;
            $monthlyData[$month]['naked_left_sum'] += $record['naked_left'];
        }
        
        if ($record['naked_right'] !== '0.0' && $record['naked_right'] !== null) {
            $monthlyData[$month]['naked_right_count']++;
            $monthlyData[$month]['naked_right_sum'] += $record['naked_right'];
        }
        
        if ($record['glasses_left'] !== '0.0' && $record['glasses_left'] !== null) {
            $monthlyData[$month]['glasses_left_count']++;
            $monthlyData[$month]['glasses_left_sum'] += $record['glasses_left'];
        }
        
        if ($record['glasses_right'] !== '0.0' && $record['glasses_right'] !== null) {
            $monthlyData[$month]['glasses_right_count']++;
            $monthlyData[$month]['glasses_right_sum'] += $record['glasses_right'];
        }
    }
   



    // 计算每个月的平均视力
    $naked_left_data = [];
    $naked_right_data = [];
    $glasses_left_data = [];
    $glasses_right_data = [];

    for ($i = 1; $i <= 12; $i++) {
        if (isset($monthlyData[$i])) {
            $naked_left_avg = $monthlyData[$i]['naked_left_count'] > 0 ? $monthlyData[$i]['naked_left_sum'] / $monthlyData[$i]['naked_left_count'] : 0;
            $naked_right_avg = $monthlyData[$i]['naked_right_count'] > 0 ? $monthlyData[$i]['naked_right_sum'] / $monthlyData[$i]['naked_right_count'] : 0;
            $glasses_left_avg = $monthlyData[$i]['glasses_left_count'] > 0 ? $monthlyData[$i]['glasses_left_sum'] / $monthlyData[$i]['glasses_left_count'] : 0;
            $glasses_right_avg = $monthlyData[$i]['glasses_right_count'] > 0 ? $monthlyData[$i]['glasses_right_sum'] / $monthlyData[$i]['glasses_right_count'] : 0;
        } else {
            $naked_left_avg = 0;
            $naked_right_avg = 0;
            $glasses_left_avg =0;
            $glasses_right_avg = 0;
        }

        $naked_left_data[] = $naked_left_avg;
        $naked_right_data[] = $naked_right_avg;
        $glasses_left_data[] = $glasses_left_avg;
        $glasses_right_data[] = $glasses_right_avg;
    }

// 对数据进行格式化，保留两位小数
$glasses_right_data = array_map(function($value) {
    return number_format($value, 1, '.', '');
}, $glasses_right_data);

$glasses_left_data = array_map(function($value) {
    return number_format($value, 1, '.', '');
}, $glasses_left_data);

$naked_left_data = array_map(function($value) {
    return number_format($value, 1, '.', '');
}, $naked_left_data);

$naked_right_data = array_map(function($value) {
    return number_format($value, 1, '.', '');
}, $naked_right_data);

    

    return $this->success('查询成功','',[
        [
            'name' => '戴镜右眼',
            'data' => $glasses_right_data,
            'type' => 'line'
        ],
        [
            'name' => '戴镜左眼',
            'data' => $glasses_left_data,
            'type' => 'line'
        ],
        [
            'name' => '裸眼左眼',
            'data' => $naked_left_data,
            'type' => 'line'
        ],
        [
            'name' => '裸眼右眼',
            'data' => $naked_right_data,
            'type' => 'line'
        ],
    ]);
   }

 /**
     * 查看
     */
    public function index()
    {    

    if($this->request->isAjax()){
     return  $this->success('查询成功','',$this->getData());
    };
        
        
        $this->view->assign("typeList", Db::name('school')->field('id,schoolname')->select());

        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }
    
    /**
     * 
     * 渲染图表数据
     * 获取裸眼 戴镜的人数数据
     */
    public function getData(){
       // 获取请求参数
       $vision1 = $this->request->post('schoolname', '');
       if (empty($vision1)) {
           $this->error('未选择学校！请先选择学校');
       }
    $vision = $this->request->post('left', '');
    if (empty($vision)) {
        $this->error('参数错误：未提供视力值');
    }
  // 初始化查询条件
  $where = [];
  $grade = $this->request->post('grade');
  $year = $this->request->post('year');
  $month = $this->request->post('month');
  $classd = $this->request->post('classd');
  // 动态添加查询条件
  $where['schoolname'] = $vision1;
  if (!empty($grade)) {
 
      $where['grade'] =  $this->request->post('grade');
  }
 
  if (!empty($classd)) {
  
      $where['classd'] =$this->request->post('classd');
  }
  if (!empty($year)) {
 
    $where['year'] =  $this->request->post('year');
}

if (!empty($month)) {

    $where['month'] =$this->request->post('month');
}




    // 检查请求参数是否为空
 

        // 获取所有相关的记录
        $records = Db::name('student_reports')
            ->where($where)
            ->select();
    
        // 初始化计数器
        $naked_left_count = 0;
        $naked_right_count = 0;
        $glasses_left_count = 0;
        $glasses_right_count = 0;
    
        // 遍历记录并统计数量
        foreach ($records as $record) {
            if ($record['naked_left'] == $vision) {
                $naked_left_count++;
            }
            if ($record['naked_right'] == $vision) {
                $naked_right_count++;
            }
            if ($record['glasses_left'] == $vision) {
                $glasses_left_count++;
            }
            if ($record['glasses_right'] == $vision) {
                $glasses_right_count++;
            }
        }
       
    
        // 返回结果
        return [
            'data' => [
                ['value' => $naked_left_count , 'name' => '裸眼左眼人数'],
                ['value' => $naked_right_count , 'name' => '裸眼右眼人数'],
                ['value' => $glasses_left_count , 'name' => '戴镜左眼人数'],
                ['value' => $glasses_right_count , 'name' => '戴镜右眼人数']
            ],
         
        ];
    }
}
